package com.kornero.geek.core;

import java.util.Calendar;
import java.util.Observable;

public class Timer extends Observable {

    private static final String TAG = Timer.class.getSimpleName();

    private Thread tickerThread = new Thread(new TimerTick());
    private volatile Calendar calendar;
    private final int tickTime;

    public Timer(final int tickTime) {
        this.tickTime = tickTime;
    }

    public void startFrom(final Calendar calendar) {
        this.stop();

        this.calendar = calendar;

        this.tickerThread = new Thread(new TimerTick());
        this.tickerThread.start();
    }

    public void stop() {
        if (null != this.tickerThread) {
            this.tickerThread.interrupt();
        }
    }

    public Calendar getCalendar() {
        return this.calendar;
    }

    private class TimerTick implements Runnable {

        @Override
        public void run() {
            final Thread me = Thread.currentThread();
            while (!me.isInterrupted()) {
                this.doTick();
                notifyObservers(getCalendar());
            }
        }

        private void doTick() {
            try {
                Thread.sleep(tickTime);
            } catch (InterruptedException e) {

                // Okay, do not panic! Nothing bad happens.
                Thread.currentThread().interrupt();
            }
            calendar.add(Calendar.MINUTE, 1);
            setChanged();
        }
    }
}